<template>

  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" :before-close="handleClose"
      :close-on-click-modal="false">
      <el-form :inline="false" :model="formInline" ref="parameter-add-form" :rules="formRules" class="demo-form-inline"
        v-loading="loadingForm" label-width="100px">

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="参数名称:" prop="goodsParameterName">
              <el-input v-model="formInline.goodsParameterName" class="cell-input" placeholder="请输入参数名称">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品类目:" prop="goodsCategoryId">
              <div class="cell-input">
                <treeselect v-model="formInline.goodsCategoryId" :options="menuOptions" :normalizer="normalizer"
                  :show-count="true" placeholder="主类目" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="排序号:" prop="parameterSort">
              <el-input-number v-model="formInline.parameterSort" class="cell-input" :controls="false"
                style="text-align: left;" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="参数值:" prop="parameterList">
              <el-button type="" icon="el-icon-plus" @click="handleAddParameter">添加</el-button>
              <div>
                <vue-draggable v-model="formInline.parameterList" chosen-class="chosen" force-fallback="true"
                  animation="300" handle=".el-icon-sort">
                  <transition-group>
                    <div style="margin-top:12px;" v-for="(item,index) in formInline.parameterList" :key="index">
                      <el-input v-model="item.name" class="cell-input" placeholder="请输入数值" />
                      <i class="el-icon-sort"
                        style="margin-left: 20px; font-size: 22px;vertical-align: middle;cursor: move;"></i>
                      <el-button size="mini" style="margin-left: 8px;" v-if="index != 0" type="danger"
                        icon="el-icon-delete" circle @click="handleDelParameter(index)"></el-button>
                    </div>
                  </transition-group>
                </vue-draggable>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="!loadingForm">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    updataWcGoodsParameter,
    findWcGoodsParameter,
    addWcGoodsParameter
  } from "@/api/culturalCreativity/parameter.js";
  import {
    listWcGoodsCategory
  } from "@/api/culturalCreativity/category.js";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  let _this;
  export default {
    name: "EaaAdd",
    components: {
      Treeselect
    },
    data() {
      return {
        title: '',
        id: null,
        dialogVisible: false,
        formRules: {
          parameterSort: {
            required: true,
            message: '请输入排序号',
            trigger: 'blur'
          },
          parameterList: {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              for (let i in value) {
                if (!value[i].name) return callback(new Error('请输入内容'))
              }
              callback();
            }
          },
          goodsCategoryId: {
            required: false,
            message: '请选择商品类目',
            trigger: 'change'
          },
          goodsParameterName: {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        },
        formInline: {},
        loadingScreen: null,
        loadingForm: false,
        fileName: '',
        btnLoading: false,
        menuOptions: [],
        listCategoryData: []
      }
    },
    methods: {
      async init(id) {
        try {
          _this = this;
          this.title = '';
          this.resetFrom();
          this.dialogVisible = true;
          if (this.$refs['parameter-add-form']) this.$refs['parameter-add-form'].resetFields();
          await this.getLeiMu();
          if (!id) return this.title = '新增';
          this.title = '修改'
          this.loadingForm = true;
          let res = await findWcGoodsParameter(id);
          this.loadingForm = false;
          this.formInline.goodsParameterId = id;
          Object.keys(this.formInline).forEach(item => {
            this.formInline[item] = res.data[item];
          });
          this.formInline.parameterList = this.formInline.parameter.split(",").map(name => {
            return {
              name
            }
          });
        } catch (e) {
          this.loadingForm = false;
        }
      },
      handleDelParameter(index) { //删除
        let data = this.formInline.parameterList;
        this.formInline.parameterList = [...data.slice(0, index), ...data.slice(index + 1, data.length)];
        this.$refs['parameter-add-form'].validateField("parameterList");
      },
      handleAddParameter() {
        this.formInline.parameterList.push({
          name: ""
        })
      },
      async getLeiMu() {
        this.menuOptions = [];
        let res = await listWcGoodsCategory({}, {
          pageNum: 1,
          pageSize: 99999,
        });
        this.listCategoryData = res.rows;
        const menu = {
          goodsCategoryId: '',
          goodsCategoryName: '主类目',
          children: []
        };
        menu.children = this.handleTree(res.rows, "goodsCategoryId", "goodsCategoryParentId");
        this.menuOptions.push(menu);
        return;
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.goodsCategoryId,
          label: node.goodsCategoryName,
          children: node.children
        };
      },
      resetFrom() {
        this.formInline = {
          parameterSort: "",
          parameter: "",
          parameterList: [],
          goodsCategoryId: "",
          goodsParameterName: ""
        };
      },
      handleClose() {
        this.dialogVisible = false;
      },
      handleSubmit() {
        this.$refs['parameter-add-form'].validate(async valid => {
          try {
            if (valid) {
              let formInline = {
                ...this.formInline
              };
              formInline.parameter = formInline.parameterList.map(item => item.name).join(",");
              delete formInline.parameterList;
              formInline.goodsCategoryName = this.listCategoryData.reduce((pev, item) => {
                if (item.goodsCategoryId == formInline.goodsCategoryId) {
                  pev = item.goodsCategoryName
                };
                return pev
              }, "");
              let res;
              this.btnLoading = true;
              if (!this.formInline.goodsParameterId) {
                res = await addWcGoodsParameter(formInline);
                this.$message.success("添加成功");
              } else {
                res = await updataWcGoodsParameter(formInline);
                this.$message.success("更新成功");
              }
              this.btnLoading = false;
              this.dialogVisible = false;
              this.$emit("success");
            }
          } catch (e) {
            this.btnLoading = false;
          }
        });
      },
    },
    created() {
      this.resetFrom();
    },
    computed: {}
  }
</script>
<style lang="scss" scoped>
  ::v-deep .el-input__inner {
    text-align: left;
  }

  .width100 {
    width: 590px;
  }

  .cell-input {
    width: 200px;
  }

  .up-file-wrappar {
    display: flex;
    align-items: center;
  }

  .total-day {
    display: inline-block;
    height: 36px;
    width: 40px;
    margin: 0 6px;
    text-align: center;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    padding: 0 15px;
    box-sizing: border-box;
  }

  .up-file-name {
    display: inline-block;
    height: 36px;
    min-width: 555px;
    text-align: left;
    line-height: 36px;
    box-sizing: border-box;
    padding: 0 15px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    color: #606266;
    font-size: inherit;

    .text {
      display: -webkit-box;
      overflow: hidden;
      white-space: normal !important;
      text-overflow: ellipsis;
      word-wrap: break-word;
      -webkit-line-clamp: 1; //行数
      -webkit-box-orient: vertical;
      max-width: 555px;
    }
  }
</style>
